package com.example.flutter_ad_demo

import android.os.Bundle
import android.util.Log
import android.widget.FrameLayout
import androidx.fragment.app.FragmentActivity
import com.bwt.top.SplashAd
import com.bwt.top.SplashAdListener
import com.bwt.top.ad.bean.AdInfo
import com.bwt.top.exception.AdError
import com.bwt.top.util.DisplayUtil

class SplashAdActivity : FragmentActivity() {
    companion object {
        private const val TAG = "BWTSplashAd"
    }
    private var splashAd: SplashAd? = null
    private var ready = false
    private var jumped = false
    private var readyJump = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash_ad)

        val flContainer = findViewById<FrameLayout>(R.id.flContainer)

        // 其他相关的配置请参考文档
        splashAd = SplashAd(this, flContainer)
        // TODO 替换为自己的广告位ID
        splashAd?.setAdId("14303340")
        splashAd?.setSkipViewToTop()
        splashAd?.isImmersive = true

        splashAd?.skipTime = 5000L
        splashAd?.adListener = object : SplashAdListener() {
            override fun onAdReceive(adInfo: AdInfo?) {
                Log.d(TAG, "onAdReceive::::::")
            }

            override fun onAdExpose(adInfo: AdInfo?) {
                Log.d(TAG, "onAdExpose::::::")
            }

            override fun onAdClick(adInfo: AdInfo?) {
                Log.d(TAG, "onAdClick::::::")
            }

            override fun onAdClose(adInfo: AdInfo?) {
                Log.d(TAG, "onAdClose::::::")
                readyThenCheckJump()
            }

            override fun onAdFailed(adInfo: AdError?) {
                Log.d(TAG, "onAdFailed::::::${adInfo?.errorCode()}, ${adInfo?.errorMsg()}")
                readyThenCheckJump()
            }

            override fun onAdTick(time: Long) {
            }

            override fun onAdSkip(adInfo: AdInfo?) {
                Log.d(TAG, "onAdSkip::::::")
                readyThenCheckJump()
            }
        }

        Log.d(TAG, "onAdLoad::::::")
        splashAd?.loadAd()
    }

    private fun readyThenCheckJump() {
        ready = true
        checkJump()
    }

    private fun checkJump() {
        if (ready && readyJump && !jumped) {
            ready = false
            jumped = true
            finish()
        }
    }
}